/**
 * @author 徐楠
 * @date 2022/2/17 9:26
 * @version 1.0
 */

package com.xunan.likou;

/**
 * 实现 strStr()
 */
public class AchieveStrStr {
    public static void main(String[] args) {
        String haystack = "mississippi";
        String needle = "issipi";
        //System.out.println(haystack.charAt(0)=='1');
        int result = strStr(haystack, needle);
        System.out.println("===");
        System.out.println(result);
        //System.out.println(result);
    }

    public static int strStr(String haystack, String needle) {
        if (haystack.length() == 0 && needle.length() == 0) {
            return 0;
        }
        if (haystack.length() != 0 && needle.length() == 0) {
            return 0;
        }
        if ((haystack.length() == 0 && needle.length() != 0) || haystack.length() < needle.length()) {
            return -1;
        }
        for (int i = 0; i < haystack.length(); i++) {
            int temp = i;
            if (haystack.charAt(i) == needle.charAt(0)) {
                int n = 0;
                for (int j = 0; j < needle.length() && temp < haystack.length(); j++) {
                    if (needle.charAt(j) == haystack.charAt(temp)) {
                        temp++;
                        n++;
                        if (n == needle.length()) {
                            return i;
                        }
                        continue;
                    } else {
                        break;
                    }
                }
            }
        }

        return -1;

    }

    public static int strStr1(String haystack, String needle) {
        int n = haystack.length(), m = needle.length();
        for (int i = 0; i + m <= n; i++) {
            boolean flag = true;
            for (int j = 0; j < m; j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return i;
            }
        }
        return -1;
    }



}
